package sg.edu.nus.iss.billing.ui.gui;

import java.util.*;

import javax.swing.*;
import javax.swing.GroupLayout.ParallelGroup;
import javax.swing.GroupLayout.SequentialGroup;

import sg.edu.nus.iss.billing.common.exception.BadDbCallException;
import sg.edu.nus.iss.billing.service.login.Administrator;
import sg.edu.nus.iss.billing.service.login.CallAgent;
import sg.edu.nus.iss.billing.ui.controller.OneBillingSystem;
import sg.edu.nus.iss.billing.vo.subscription.CableTvVO;
import sg.edu.nus.iss.billing.vo.subscription.DigitalVoiceVO;
import sg.edu.nus.iss.billing.vo.subscription.MobileVoiceVO;
import sg.edu.nus.iss.billing.vo.subscription.SubscriptionVO;
import sg.edu.nus.iss.billing.vo.subscription.feature.ChannelFeatureVO;
import sg.edu.nus.iss.billing.vo.subscription.feature.FeatureVO;


import java.awt.Dimension;
import java.awt.FlowLayout;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyVetoException;

public class CableTVPanel  extends JPanel {

	private static final long serialVersionUID = 1L;
	private TabbedFrame parent;
	private OneBillingSystem onebillingsystem;
	private CableTvVO cabletvplan;
	@SuppressWarnings("unused")
	private CableTvVO subscribedcableTvVO;
	private ArrayList<ChannelFeatureVO> subscribedoptionalfeatures;
	
	JPanel selectionPanel;
	JPanel basicFeaturePanel;
	JPanel optionalFeaturePanel;
	JPanel buttonPanel;
	
	JCheckBox chkexclude;
	
	public CableTVPanel(TabbedFrame parent, OneBillingSystem onebillingsystem){
		this.parent= parent;
		this.onebillingsystem=onebillingsystem;
		Iterator<SubscriptionVO> iterator = parent.getAvailableplanoptions().iterator();
		SubscriptionVO plan;
		while (iterator.hasNext()) {
			plan= iterator.next();
			if( plan instanceof CableTvVO){
				cabletvplan = (CableTvVO) plan;
			}
		}

		Iterator<SubscriptionVO> iterator2 = parent.getSubscripedplanoptions().iterator();
		SubscriptionVO plan2;
		while (iterator2.hasNext()) {
			plan2= iterator2.next();
			if( plan2 instanceof CableTvVO){
				subscribedcableTvVO = (CableTvVO) plan2;
			}
		}
		if(subscribedcableTvVO==null){
			subscribedcableTvVO = new CableTvVO();
		}
		subscribedoptionalfeatures= subscribedcableTvVO.getAllAddonChannel();
		
		selectionPanel=createSelectionPanel();
		basicFeaturePanel=createBasicFeaturePanel();
		optionalFeaturePanel=createOptionalFeaturePanel();
		buttonPanel=createButtonPanel();
	
		 GroupLayout layout = new GroupLayout(this);
	       setLayout(layout);
	        layout.setHorizontalGroup(
	            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(layout.createSequentialGroup()
	                //.addGap(24, 24, 24)
	                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
	                    .addComponent(selectionPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
	                    .addComponent(basicFeaturePanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
	                    .addComponent(optionalFeaturePanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
	                    .addComponent(buttonPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
	                .addContainerGap(108, Short.MAX_VALUE))
	        );
	        layout.setVerticalGroup(
	            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
	            .addGroup(layout.createSequentialGroup()
	               // .addGap(29, 29, 29)
	                .addComponent(selectionPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
	                .addComponent(basicFeaturePanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
	                .addComponent(optionalFeaturePanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
	                .addComponent(buttonPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
	                .addContainerGap(214, Short.MAX_VALUE))
	        );
	        

	}
	
	private void performchkexcludeChange(){
		if(!chkexclude.isSelected()){
        	basicFeaturePanel.setVisible(true);
        	optionalFeaturePanel.setVisible(true);
        	parent.setSubscripedplanoptions(parent.getTab().getSelectedIndex(),subscribedcableTvVO);
        }
        else{
            	basicFeaturePanel.setVisible(false);
            	optionalFeaturePanel.setVisible(false);
            	parent.getHtsubscripedplanoptions().remove(parent.getTab().getSelectedIndex());
        	}
	}
	
	//this method will update the subscribed plan list
	private void performchkboxChange(ActionEvent e){
		JCheckBox checkbox = (JCheckBox)e.getSource();
		System.out.println(checkbox.getText());
		System.out.println(checkbox.isSelected());
		if(checkbox.isSelected()){
			Iterator<ChannelFeatureVO> iterator = cabletvplan.getAllAddonChannel().iterator();
			while(iterator.hasNext()){
				ChannelFeatureVO optfeature = iterator.next();
				if(optfeature.getDescription().equals(checkbox.getText())){
					subscribedoptionalfeatures.add(optfeature);
					break;
				}
			}
			System.out.println(subscribedoptionalfeatures.size());
		}
		else{
			Iterator<ChannelFeatureVO> iterator = subscribedoptionalfeatures.iterator();
			while(iterator.hasNext()){
				FeatureVO optfeature = iterator.next();
				if(optfeature.getDescription().equals(checkbox.getText())){
					subscribedoptionalfeatures.remove(optfeature);
					break;
				}
			}
			System.out.println(subscribedoptionalfeatures.size());
		}
		subscribedcableTvVO.setAddonChannel(subscribedoptionalfeatures);
		parent.setSubscripedplanoptions(parent.getTab().getSelectedIndex(),subscribedcableTvVO);
	}
	
	private JPanel createSelectionPanel( ){
		JPanel p = new JPanel ();
		p.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)),""));
		
		chkexclude=new JCheckBox("Exculde Cable TV ");
		p.add(chkexclude);
		p.setPreferredSize(new Dimension(350, 60));
		
		chkexclude.addActionListener (new ActionListener () {
	            public void actionPerformed (ActionEvent e) {
	            	performchkexcludeChange();
	            		
	            }
	        });
		 
		 GroupLayout layout = new GroupLayout(p);
	        p.setLayout(layout);
	        layout.setHorizontalGroup(
	            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(layout.createSequentialGroup()
	                .addGap(15, 15, 15)
	                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
	                    .addComponent(chkexclude, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
	                .addContainerGap(20, Short.MAX_VALUE))
	        );
	        layout.setVerticalGroup(
	            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
	            .addGroup(layout.createSequentialGroup()
	                .addGap(15, 15, 15)
	                .addComponent(chkexclude, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
	                .addContainerGap(20, Short.MAX_VALUE))
	        );
		return p;
	}
	
	private JPanel createBasicFeaturePanel(){
		JPanel p = new JPanel ();
		 p.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)),"Basic Feature"));
		List<JCheckBox> checkboxlist = new ArrayList<JCheckBox>();
		JCheckBox checkbox;

		for(int iCount=0;iCount< cabletvplan.get3StandardChannels().size();iCount++ ){
			checkbox= new JCheckBox(cabletvplan.get3StandardChannels().get(iCount).getName(), true);
			checkbox.setEnabled(false);
			checkbox.addActionListener (new ActionListener () {
	            public void actionPerformed (ActionEvent e) {
	            	performchkboxChange(e);
	            }
	        });
			checkboxlist.add(checkbox);
		}

		
		GroupLayout layout = new GroupLayout(p);
        p.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
            		 .addGap(24, 24, 24)
	                    .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
	                        .addComponent(checkboxlist.get(0))
	                        .addComponent(checkboxlist.get(2))
                   		)
	                    .addGap(24, 24, 24)
	                    .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
	                    		.addComponent(checkboxlist.get(1)))
	                    		 .addContainerGap(214, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createSequentialGroup()//(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addComponent(checkboxlist.get(0))
                        .addComponent(checkboxlist.get(1)))
                    		)
                    .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addComponent(checkboxlist.get(2))
                  		)
        );
    p.setPreferredSize(new Dimension(350, 100));
	return p;
	}
	
	private JPanel createOptionalFeaturePanel(){
		JPanel p = new JPanel ();
		p.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)),"Optional Features"));

		List<JCheckBox> checkboxlist = new ArrayList<JCheckBox>();
		JCheckBox checkbox;
		
		Iterator<ChannelFeatureVO> iterator = cabletvplan.getAllAddonChannel().iterator();
		while(iterator.hasNext()){
			ChannelFeatureVO feature;
			feature= iterator.next();
			System.out.println("feature1 In createOptionalFeaturePanel Myself");
			System.out.println("feature1 Myself "+ feature.getDescription());
			System.out.println("feature1 Myself" + feature.getName());
			checkbox= new JCheckBox(feature.getDescription(), false);
			checkbox.setEnabled(true);
			checkboxlist.add(checkbox);
			System.out.println("subscribedcableTvVO.getAllAddonChannel(): "+subscribedcableTvVO.getAllAddonChannel().size());
			
			Iterator<ChannelFeatureVO> iterator2 = subscribedcableTvVO.getAllAddonChannel().iterator();
			while(iterator2.hasNext()){
				ChannelFeatureVO feature2;
				feature2= iterator2.next();
				
				System.out.println("Before IF CONDITION feature1" + feature.getDescription());
				System.out.println("Before IF CONDITION  feature2" + feature2.getDescription());
				
				if(feature2.getDescription().equalsIgnoreCase(feature.getDescription())){
					checkbox.setSelected(true);
					System.out.println("feature1" + feature.getDescription());
					System.out.println("feature2" + feature2.getDescription());
				}
			}
			checkbox.addActionListener (new ActionListener () {
	            public void actionPerformed (ActionEvent e) {
	            	performchkboxChange(e);
	            }
	        });
			
		}
		


		 GroupLayout layout = new GroupLayout(p);
	        p.setLayout(layout);
	        
			ParallelGroup parallelgroup =layout.createParallelGroup(GroupLayout.Alignment.LEADING);
			
			ParallelGroup parallelgroup2 =layout.createParallelGroup(GroupLayout.Alignment.LEADING);
			 System.out.println("B4 number");
			 System.out.println(checkboxlist.size());
			 for(int i=0;i<checkboxlist.size();i++){
				 if(i%2==0){
					 System.out.println(i);
					 parallelgroup.addComponent(checkboxlist.get(i));
				 }
				 else{
					 parallelgroup2.addComponent(checkboxlist.get(i));
				 }
			 }
			
	        SequentialGroup seqgroup =  layout.createSequentialGroup();
	        ParallelGroup parallelgroup3=null;
	        //parallelgroup3 = layout.createParallelGroup(GroupLayout.Alignment.LEADING);
	        for(int i=0;i<checkboxlist.size();i++){
	        if(i%2==0){
	        	parallelgroup3 = layout.createParallelGroup(GroupLayout.Alignment.LEADING);

	        }
        	parallelgroup3.addComponent(checkboxlist.get(i));
	        if(i%2!=0){
	        	seqgroup.addGroup(parallelgroup3);
	        }
	        }
	        if(checkboxlist.size() % 2!=0){
	        	seqgroup.addGroup(parallelgroup3);
	        }
			

/*
			
	        layout.setHorizontalGroup(
	            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(layout.createSequentialGroup()
	            		 .addGap(24, 24, 24)
	                    .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
	                        .addComponent(checkboxlist.get(0))
	                        .addComponent(checkboxlist.get(2))
	                        .addComponent(checkboxlist.get(4))
	                        .addComponent(checkboxlist.get(6))
	                    		)
	                    .addGap(24, 24, 24)
	                    .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
	                    		.addComponent(checkboxlist.get(1))
	                    		.addComponent(checkboxlist.get(3))
	                    		.addComponent(checkboxlist.get(5))
	                    		.addComponent(checkboxlist.get(7)))
	                    		 .addContainerGap(214, Short.MAX_VALUE))
	        );
	        */

	        layout.setHorizontalGroup(
	            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(layout.createSequentialGroup()
	            		 .addGap(24, 24, 24)
	                    .addGroup(parallelgroup	)
	                    .addGap(24, 24, 24)
	                    .addGroup(parallelgroup2)
	                    		 .addContainerGap(214, Short.MAX_VALUE))
	        );
	        
	        /*
	        layout.setVerticalGroup(
	            layout.createSequentialGroup()//(GroupLayout.Alignment.LEADING)
	            .addGroup(layout.createSequentialGroup()
	                    .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
	                        .addComponent(checkboxlist.get(0))
	                        .addComponent(checkboxlist.get(1)))
	                    .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
	                       .addComponent(checkboxlist.get(2))
	                       .addComponent(checkboxlist.get(3)))
	                    .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
	                        .addComponent(checkboxlist.get(4))
	                        .addComponent(checkboxlist.get(5)))
	                   .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
	                        .addComponent(checkboxlist.get(6))
	                        .addComponent(checkboxlist.get(7)))
	                        )

	        );*/
	        layout.setVerticalGroup(
		            layout.createSequentialGroup()//(GroupLayout.Alignment.LEADING)
		            .addGroup(seqgroup
		                        )

		        );

	        
	    p.setPreferredSize(new Dimension(350, 220));
		return p;
	}
	
	private JPanel createButtonPanel () {

        JPanel p = new JPanel ();

        JButton previous = new JButton ("Previous");
        previous.addActionListener (new ActionListener () {
            public void actionPerformed (ActionEvent e) {
            	parent.getTab().setSelectedIndex(parent.getTab().getSelectedIndex()-1);
            }
        });
        p.add (previous);
        
        JButton save = new JButton ("Save");
    	if(onebillingsystem.getUser().getClass() == CallAgent.class){
    		save.setEnabled(false);
	    	}
        save.addActionListener (new ActionListener () {
            public void actionPerformed (ActionEvent e) {
            	//parent.getAccount().setListSubscriptionVO(parent.getSubscripedplanoptions());
            	try {
            		ArrayList<SubscriptionVO> subscripedplans = new ArrayList<SubscriptionVO>();
            		System.out.println("HASH TABLE SIZE = "+parent.getHtsubscripedplanoptions().size());
            		for(int i=0; i<parent.getHtsubscripedplanoptions().size();i++){
            			if(parent.getHtsubscripedplanoptions().get(i) !=null){
            				parent.getHtsubscripedplanoptions().get(i).setAccNo(parent.getAcctNo());
            			subscripedplans.add(parent.getHtsubscripedplanoptions().get(i));
            			}
            		}
            		parent.getAccount().setListSubscriptionVO(subscripedplans);
            		System.out.println("Cable TV Panel: SUBSCRIPTION SAVE ACTION");
            		System.out.println("ACCT No :" + parent.getAccount().getAccountNo());
            		System.out.println("Subs Count :" + parent.getAccount().getListSubscriptionVO().size());
            		Iterator<SubscriptionVO> itr = parent.getAccount().getListSubscriptionVO().iterator();
            		while(itr.hasNext()){
            			SubscriptionVO sub= itr.next();
            			System.out.println(sub.getName());
            			if( sub instanceof DigitalVoiceVO){
            				DigitalVoiceVO dv = (DigitalVoiceVO)sub;
            				System.out.println("In DIGITAL VOICE");
            				System.out.println(dv.getAccNo());
            				System.out.println("Number of Opt Features"+dv.getAllOptionalFeature().size());
            				Iterator<FeatureVO> itr2 = dv.getAllOptionalFeature().iterator();
            				while(itr2.hasNext()){
            					FeatureVO fv = itr2.next();
            					System.out.println("Feature Name : "+fv.getName());
            					System.out.println("Feature Desc : "+fv.getDescription());
            				}
            				
            			}
						if( sub instanceof MobileVoiceVO){
							System.out.println("In MOBILE VOICE");
							MobileVoiceVO mv = (MobileVoiceVO)sub; 
            				System.out.println(mv.getAccNo());
            				System.out.println("Number of Opt Features"+mv.getAllOptionalFeature().size());
            				Iterator<FeatureVO> itr2 = mv.getAllOptionalFeature().iterator();
            				while(itr2.hasNext()){
            					FeatureVO fv = itr2.next();
            					System.out.println("Feature Name : "+fv.getName());
            					System.out.println("Feature Desc : "+fv.getDescription());
            				}
						}
						if( sub instanceof CableTvVO){
							System.out.println("In CABLE TV");
							CableTvVO cv = (CableTvVO)sub;
						}
            		}
            		
					((Administrator)onebillingsystem.getUser()).modifySubscription(parent.getAccount());
					JOptionPane.showMessageDialog(null,"Subscription saved successfully","",JOptionPane.CLOSED_OPTION);
					parent.setClosed(true);
				} catch (BadDbCallException e1) {
					e1.printStackTrace();
				} catch (PropertyVetoException e2) {
					e2.printStackTrace();
				}
            }
        });
        p.add (save);
        
        JButton close = new JButton ("Close");
        close.addActionListener (new ActionListener () {
            public void actionPerformed (ActionEvent e) {
            	try {
					parent.setClosed(true);
				} catch (PropertyVetoException e1) {

				}
            }
        });
        p.add (close);

        JPanel bp = new JPanel ();
        bp.setLayout (new FlowLayout());
        bp.add (p);
        return bp;
    }

}
